#!/usr/bin/env perl

BEGIN {
	push @INC,".." if -f "../pv2.pm";
	push @INC,$ENV{CODEMGR_LIBS} if exists($ENV{CODEMGR_LIBS});
}

use pv2;
use Getopt::Long;
use strict;

$::ARG_pv=undef;
$::ARG_version=undef;

sub usage {
	print "
Usage: pv2_upgrade [-p DIR] file ...

The pv2_upgrade takes an existing pv2 file and updates it to
the latest version if needed.

Written by Simon Edwards, (C) 2006-2010 www.advantsys.co.uk
";
	exit 1;
}
$::ARG_pv=undef;
if(!GetOptions(
	"pv=s"		=> \$::ARG_pv,
	)) {
	usage;
}

if(-d "PV2" && !defined($::ARG_pv)) {$::ARG_pv="PV2";}
if(-d ".PV2" && !defined($::ARG_pv)) {$::ARG_pv=".PV2";}
my %args=();

for my $cfile (@ARGV) {
	next if -d $cfile;
	if(defined($::ARG_pv) && -f "$::ARG_pv/$cfile,pv") {
		$args{PVFILE}="$::ARG_pv/$cfile,pv" if defined($::ARG_pv);
	} elsif($cfile =~ /,pv$/ && -f $cfile) {
		$args{PVFILE}=$cfile;
	} elsif(-f "$cfile,pv") {
		$args{PVFILE}="$cfile,pv";
	} else {
		next;
	} 
		
	my ($rc,$pv)=pv::pv_update_to_latest_version(%args);
	if($rc==1) {
		if(defined($pv)) {
			print "$cfile - OK: $pv\n";
		} else {
			print "$cfile - OK\n";
		}
	} else {
		print "$cfile - ERROR: $pv\n";
	}
}
exit(0);

